<template>

	<!--盘点范围-->
	<div class="bill-detail-title">盘点范围</div>
	<a-divider class="divider-center"/>
	<a-row >
		<a-col :span="8">
			<a-form :model="props.submitFormData.header" ref="checkRef" :label-col="{ span: 6 }" :wrapper-col="{ span: 14 }">
				<a-form-item  name="wareId">
					<template #label>
							<span>
							  盘点仓库
							  <a-tooltip title="为空则盘点全部仓库">
									<QuestionCircleOutlined />
							  </a-tooltip>
							</span>
					</template>
					<a-tree-select
						v-model:value="props.submitFormData.header.wareId"
						show-search
						style="width: 100%"
						:dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
						placeholder="请选择盘点仓库"
						allow-clear
						tree-default-expand-all
						:tree-data="wareTypeTreeData"
						:field-names="{
							  children: 'children',
							  label: 'wareName',
							  value: 'wareId',
							}"
						tree-node-filter-prop="wareName"
					></a-tree-select>
				</a-form-item>
			</a-form>
		</a-col>
<!--		<a-col :span="8">-->
<!--			<a-form-item label="商品类型：" name="productTypeId">-->
<!--				<a-tree-select-->
<!--					v-model:value="props.submitFormData.header.productTypeId"-->
<!--					show-search-->
<!--					style="width: 100%"-->
<!--					:dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"-->
<!--					placeholder="请选择上级类型"-->
<!--					allow-clear-->
<!--					tree-default-expand-all-->
<!--					:tree-data="treeProductTypeData"-->
<!--					:field-names="{-->
<!--							  children: 'children',-->
<!--							  label: 'productTypeName',-->
<!--							  value: 'productTypeId',-->
<!--							}"-->
<!--					tree-node-filter-prop="productTypeName"-->
<!--				></a-tree-select>-->

<!--			</a-form-item>-->
<!--		</a-col>-->
		<a-col :span="8" >
			<span style="margin-left: 30px">
				<a-button type="primary" @click="getProductList">确定范围</a-button>
			</span>
		</a-col>
	</a-row>







	<!--表单详情-->
	<span class="bill-detail-title">盘点清单</span>
	<a-divider class="divider-center"/>
	<a-form :model="props.submitFormData" ref="recordForm">

		<a-table
			:dataSource="props.submitFormData.recordList"
			:columns="columns"
			rowKey="id"
			:pagination="false"
			:scroll="{ x: 1500 }">
			<template #bodyCell="{ text, record, index, column }">
				<a-form-item
					v-if="column.dataIndex === 'productId'"
					:rules="[{ required: true, message: '商品编号必填', trigger: 'blur' }]"
					:name="['recordList', index ,'productId']">
					<a-select v-model:value="props.submitFormData.recordList[index].productId" placeholder="商品"
							  @select="fullProductSelect(record, index)"
							  :field-names="{label: 'label',value: 'productId',}"
							  :options="productData" />
				</a-form-item>
				<a-form-item
					v-if="column.dataIndex === 'productName'"
					:rules="[{ required: true, message: '商品全名必填', trigger: 'blur' }]"
					:name="['recordList', index ,'productName']">
					<a-input v-model:value="props.submitFormData.recordList[index].productName" placeholder="商品" />
				</a-form-item>
				<a-form-item
					v-if="column.dataIndex === 'productType'"
					:rules="[{ required: true, message: '商品类型', trigger: 'blur' }]"
					:name="['recordList', index ,'productType']">
					<a-input v-model:value="props.submitFormData.recordList[index].productType" placeholder="商品" />
				</a-form-item>
				<a-form-item
					v-if="column.dataIndex === 'measureUnit'"
					:rules="[{ required: true, message: '单位必填', trigger: 'blur' }]"
					:name="['recordList', index ,'measureUnit']">
					<a-input v-model:value="props.submitFormData.recordList[index].measureUnit" placeholder="单位"  />
				</a-form-item>
				<a-form-item
					v-if="column.dataIndex === 'productSpecifications'"
					:rules="[{ required: true, message: '规格必填', trigger: 'blur' }]"
					:name="['recordList', index ,'productSpecifications']">
					<a-input v-model:value="props.submitFormData.recordList[index].productSpecifications" placeholder="商品规格" />
				</a-form-item>

				<a-form-item
					v-if="column.dataIndex === 'wareId' "
					:rules="[{ required: true, message: '仓库必填', trigger: 'blur' }]"
					:name="['recordList', index ,'wareId']">
					<a-tree-select
						v-model:value="props.submitFormData.recordList[index].wareId"
						:dropdown-style="{ maxHeight: '400px', overflow: 'auto', minWidth: '300px' }"
						show-search
						placeholder="请选择入库仓库"
						allow-clear
						tree-default-expand-all
						:tree-data="wareTypeTreeData"
						:field-names="{
							  children: 'children',
							  label: 'wareName',
							  value: 'wareId',
							}"
						tree-node-filter-prop="wareName"
					></a-tree-select>
				</a-form-item>

				<a-form-item
					v-if="column.dataIndex === 'bookCount'"
					:name="['recordList', index ,'bookCount']" >
					<a-input-number disabled v-model:value="props.submitFormData.recordList[index].bookCount"  placeholder="系统库存数量" />
				</a-form-item>
				<a-form-item
					v-if="column.dataIndex === 'count'"
					:rules="[{ required: true, message: '实际数量必填', trigger: 'blur' }]"
					:name="['recordList', index ,'count']">
					<a-input-number  v-model:value="props.submitFormData.recordList[index].count" @input="fullCount(record, index)" placeholder="实际数量" />
				</a-form-item>

				<a-form-item
					v-if="column.dataIndex === 'bigCount'"
					:name="['recordList', index ,'bigCount']" >
					<a-input-number disabled v-model:value="props.submitFormData.recordList[index].bigCount"  placeholder="多余库存" />
				</a-form-item>

				<a-form-item
					v-if="column.dataIndex === 'smallCount'"
					:name="['recordList', index ,'smallCount']" >
					<a-input-number disabled v-model:value="props.submitFormData.recordList[index].smallCount"  placeholder="缺少库存" />
				</a-form-item>

				<a-form-item :name="['recordList', index ,'remarks']" v-if="column.dataIndex === 'remarks'">
					<a-input v-model:value="record.remark" placeholder="备注" />
				</a-form-item>

				<a-button v-if="column.dataIndex === 'action'" @click="deleteRow(index)" danger>
					删除
				</a-button>
			</template>

			<template #summary>
				<a-table-summary-row>
					<a-table-summary-cell>合计</a-table-summary-cell>
					<a-table-summary-cell :colSpan="3">
						<a-typography-text ></a-typography-text>
					</a-table-summary-cell>
					<a-table-summary-cell>
						<a-typography-text >{{ totalTable.systemCount }}</a-typography-text>
					</a-table-summary-cell>
					<a-table-summary-cell >
						<a-typography-text >{{ totalTable.totalCount }}</a-typography-text>
					</a-table-summary-cell>
				</a-table-summary-row>
			</template>
		</a-table>
	</a-form>

<!--	&lt;!&ndash;	操作		&ndash;&gt;-->
<!--	<div class="modal-text-button-group">-->
<!--		<span >-->
<!--			<PlusOutlined class="modal-header-icon"/>-->
<!--			<a @click="addRow" class="modal-text-button">添加商品</a>-->
<!--		</span>-->
<!--	</div>-->
	<div style="margin-top: 60px"></div>

	<ImsBillSelector ref="billForm" type="order" @successful="billSelectorSuc"></ImsBillSelector>




</template>

<script setup>
import {ref} from "vue";
import imsProductApi from "@/api/ims/imsProductApi";
import tool from "@/utils/tool";
import ImsBillSelector from "@/components/Ims/BillSelector/index.vue";
import imsOrderApi from "@/api/ims/imsOrderApi";
import {message} from "ant-design-vue";
import imsInventoryApi from "@/api/ims/imsInventoryApi";
import imsWarehouseApi from "@/api/ims/imsWarehouseApi";
import imsProductTypeApi from "@/api/ims/imsProductTypeApi";
import imsInventoryCheckApi from "@/api/ims/imsInventoryCheckApi";

const props = defineProps({
	submitFormData: {
		type: Object,
		default: () => ({
			header: {
				userIds: [{}],
				invoiceType: '不开票',
			},
			recordList: [],
		}),
	},
	type: {
		type: String,
		default: () => ''
	},
	typeName: {
		type: String,
		default: () => ''
	},
});
const wareTypeTreeData = ref([])
const treeProductTypeData = ref([])

const productData = ref([])
const totalTable = ref({
	totalCount: 0,
	systemCount: 0
})
const texRateOptions = ref([])
const recordForm = ref(null);
const wareData = ref([])

// 动态表字段
const columns = [
	{
		title: () => {
			return h('span', [
				h('span', { style: { color: 'red', marginRight: '4px' } }, '*'),
				'商品全名'
			]);
		},
		dataIndex: 'productId',
		key: 'productId',
		width: 200,
		fixed: 'left',
	},
	{
		title: () => {
			return h('span', [
				h('span', { style: { color: 'red', marginRight: '4px' } }, '*'),
				'商品规格'
			]);
		},
		dataIndex: 'productSpecifications',
		key: 'productSpecifications',
		width: 120,
	},
	{
		title: () => {
			return h('span', [
				h('span', { style: { color: 'red', marginRight: '4px' } }, '*'),
				'单位'
			]);
		},
		dataIndex: 'measureUnit',
		key: 'measureUnit',
		width: 120
	},
	{
		title: () => {
			return h('span', [
				h('span', { style: { color: 'red', marginRight: '4px' } }, '*'),
				'仓库'
			]);
		},
		dataIndex: 'wareId',
		key: 'wareId',
		width: 140
	},

	{
		title: '系统库存数量',
		dataIndex: 'bookCount',
		key: 'bookCount',
		width: 120
	},
	{
		title: () => {
			return h('span', [
				h('span', { style: { color: 'red', marginRight: '4px' } }, '*'),
				'实际库存数量'
			]);
		},
		dataIndex: 'count',
		key: 'count',
		width: 130
	},
	{
		title: '多余库存',
		dataIndex: 'bigCount',
		key: 'bigCount',
		width: 120
	},
	{
		title: '缺少库存',
		dataIndex: 'smallCount',
		key: 'smallCount',
		width: 120
	},
	{
		title: '备注',
		dataIndex: 'remarks',
		key: 'remarks',
		width: 300
	},

	{
		title: '操作',
		dataIndex: 'action',
		key: 'action',
		width: 100,
		fixed: 'right',
	},
];


const billForm = ref()
const emit = defineEmits({ successful: null })

onMounted(() => {
	// 盘点仓库
	imsWarehouseApi.wareTree().then(res => {
		wareTypeTreeData.value = res
	})
	// 分类
	imsProductTypeApi.productTypeTree().then(res => {
		treeProductTypeData.value = res
		console.log('树选择器：', res)
	})

	// 获取商品
	imsProductApi.imsProductPage({
		current: 1,
		size: 9999
	}).then(res => {
		// 商品名称 = 商品编号+商品名称
		res.records.map(item => {
			item.label = item.productCode +'-'+ item.productName
		})
		productData.value = res.records
	})


})

// 获取清单列表
const getProductList = () => {
	imsInventoryCheckApi.getInventoryRange({
		productTypeId: props.submitFormData.header.productTypeId,
		wareId: props.submitFormData.header.wareId
	}).then(res => {
		props.submitFormData.recordList = res
		props.submitFormData.recordList.forEach((record, index) => {
			fullProductSelect(record, index)
			record.bookCount = record.count
			record.count = undefined
		})
		getTotal()
		console.log('获取清单：',props.submitFormData, res)
	})
}

// 校验
const validate = () => {
	return recordForm.value.validate();
};

// 添加一行
const addRow = () => {
	props.submitFormData.recordList.push({
		id: Date.now(),
		discount: 100,
		texRate: 0,
		planQuantity: 1
	});
};

// 删除一行
const deleteRow = (index) => {
	props.submitFormData.recordList.splice(index, 1);
};


/**
 * 选择商品回显规格和单位
 */
const fullProductSelect = (val, index) => {
	productData.value.map(item => {
		if (item.productId === val.productId) {
			props.submitFormData.recordList[index].productSpecifications = item.productSpecifications;
			props.submitFormData.recordList[index].measureUnit = item.measureUnit;
			props.submitFormData.recordList[index].univalence = item.univalence;
			props.submitFormData.recordList[index].cost = item.costPrice;
		}
	});
}

/**
 * 填充多余库存和缺少库存
 * @param val
 * @param index
 */
const fullCount = (val, index) => {
	props.submitFormData.recordList[index].bigCount = Number(val.count) - Number(val.bookCount)
	props.submitFormData.recordList[index].smallCount = Number(val.bookCount) - Number(val.count)
	// 如果props.submitFormData.recordList[index].bigCount为负数，则为0
	if (Number(val.bigCount) < 0) {
		props.submitFormData.recordList[index].bigCount = 0
	}
	// 如果props.submitFormData.recordList[index].smallCount，则为0
	if (Number(val.smallCount) < 0) {
		props.submitFormData.recordList[index].smallCount = 0
	}
	getTotal()

}
// 计算合计
const getTotal = () => {
	let count = 0;
	let systemCount = 0;
	props.submitFormData.recordList.forEach( item => {
		if (item.count) {
			count += item.count;
		}
		if (item.bookCount) {
			systemCount += item.bookCount;
		}
	})
	totalTable.value.totalCount = count
	totalTable.value.systemCount = systemCount
}



// 暴露 validate 方法
defineExpose({ validate });
</script>
